package com.stark.resume.lib.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ImageToBase64Util {
    /**
     * 图片文件转Base64（固定使用image/*前缀）
     *
     * @param filePath 图片路径
     * @param maxSize  最大文件大小（KB）
     */
    public static String convertToBase64WithPrefix(String filePath, int maxSize) throws IOException {
        Bitmap bitmap = decodeSampledBitmap(filePath, maxSize);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, baos);
        byte[] bytes = baos.toByteArray();
        String base64 = Base64.encodeToString(bytes, Base64.NO_WRAP);
        return "data:image/*;base64," + base64;
    }

    private static Bitmap decodeSampledBitmap(String path, int maxSize) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        options.inSampleSize = calculateInSampleSize(options, maxSize);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, options);
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int maxSize) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        while (true) {
            if (height / inSampleSize > 2048 || width / inSampleSize > 2048) {
                inSampleSize *= 2;
                continue;
            }

            float estimatedSize = width * height * 4 / (inSampleSize * inSampleSize * 1024f);
            if (estimatedSize > maxSize) {
                inSampleSize *= 2;
            } else {
                break;
            }
        }
        return inSampleSize;
    }
}
